<script>
    export let galleryId;

    let items = [];
    let galleryResult = Promise.resolve(true);

    const Loading = 0;
    const Success = 1;
    const Error   = 2;

    const galleryInfo = {
        kind : 0
      , name : ""
      , description : ""
    };

    const itemInfo = {
        kind : 0
      , name : ""
      , description : ""
      , files : null
    };
  
    function galleryIsValid(galleryInfo) {
        return galleryInfo.name.length; 
    }
    
    function addGallery() {
        if( galleryIsValid(galleryInfo) ) {
            galleryResult =
              fetch(
                "http://localhost:8080/galleries", {
                    method : "POST"
                 ,  headers : {
                        "Content-Type" : "application/json"
                   }
                 , credentials: "same-origin"
                 , body : JSON.stringify(galleryInfo)
                }).then( res => res.json() )
                  .then( id => galleryId = id );
        }
    }

    function updateGallery() {
        if( galleryId && galleryIsValid(galleryInfo) ) {
            galleryResult =
              fetch(
                  `http://localhost:8080/galleries/${galleryId}`, {
                    method : "POST"
                 ,  headers : {
                        "Content-Type" : "application/json"
                   }
                 , credentials: "same-origin"
                 , body : JSON.stringify(galleryInfo)
                }).then( res => res.json() );
        }
    }
    
    function itemIsValid(itemInfo) {
        return galleryId && itemInfo.files && itemInfo.files[0] && itemInfo.name.length;
    }

    function addItem() {
        if( itemIsValid(itemInfo) ) {

            const requestData = { 
                status: Loading
              , loaded : 0
              , total : 0
              , response: ""
            };

            let data = new FormData();
            let request = new XMLHttpRequest();

            data.append("itemInfo", JSON.stringify({
                name: itemInfo.name
              , description: itemInfo.description
              , kind: itemInfo.kind
            }));
           
            data.append("file", itemInfo.files[0]);
           
            request.open("POST",  `http://localhost:8080/galleries/${galleryId}/items`);

            request.upload.addEventListener("progress", (e) => {
                let {loaded, total} = e;
                requestData.loaded = loaded;
                requestData.total = total;
                // Ensure refresh
                items = items;
            });
            
            request.addEventListener("load", (e) => {
                if( request.status == 200 ||
                    request.status == 201 ) 
                    requestData.status = Success;
                else
                    requestData.status = Error;
                
                
                // Ensure refresh
                items = items;

            });
            
            request.addEventListener("readystatechange", (e) => {
                if( request.readyState === 4 && request.response.length )
                    requestData.response = JSON.parse(request.response); 
                // Ensure refresh
                items = items;
            });

            request.send(data);

            items.push({ 
                name: itemInfo.name
              , description: itemInfo.description
              , kind: itemInfo.kind
              , file : requestData
            });

            itemInfo.name = "";
            itemInfo.description = "";
            itemInfo.kind = 0;
            items = items;
        }
    }

</script>
<form>
    <fieldset>
        <legend>Gallery Information</legend>
        {#await galleryResult}
        <p>Submitting...</p>
        {:then}
        <label>Name: <input type="text" bind:value={galleryInfo.name}></label>
        <label>Description: <input type="text" bind:value={galleryInfo.description}></label>
        {#if galleryId}
        <button type="button" on:click={updateGallery} disabled={!galleryIsValid(galleryInfo)}>Update Gallery</button>
        {:else}
        <button type="button" on:click={addGallery} disabled={!galleryIsValid(galleryInfo)}>Add Gallery</button>
        {/if}
        {:catch err}
        <p>{err.message}</p>
        {/await}
    </fieldset>
    {#if galleryId}
    <fieldset>
        <legend>Gallery Items</legend>
        <ul>
        {#each items as item}
            <li>{item.name}
                {#if item.file.status === Success}
                <span class="success">Success</span>
                {:else if item.file.status === Error}
                <span class="error">Upload Failed: {item.file.response}</span>
                {:else}
                {#if item.file.total > 0}
                <progress max={item.file.total} value={item.file.loaded}></progress>
                {:else}
                <progress></progress>
                {/if}
                {/if}
            </li>
        {/each}
        </ul>
        <fieldset>
            <legend>New Item</legend>
            <label>Name: <input type="text" bind:value={itemInfo.name}></label>
            <label>Description: <input type="text" bind:value={itemInfo.description}></label>
            <label>File: <input type="file" bind:files={itemInfo.files}></label>
            <button type="button" on:click={addItem} disabled={!itemIsValid(itemInfo)}>Add Item</button>
        </fieldset>
    </fieldset>
    {/if}
</form>
